/*
 * @Description:
 * @User: Vijay <1937832819@qq.com>
 * @Date: 2020-10-20 22:34:11
 */
/**
 * Description:
 * User: Vijay <1937832819@qq.com>
 * Date: 2020/08/19
 * Time: 10:20
 */

package models

import (
	"time"

	"github.com/astaxie/beego/orm"
	"gorm.io/gorm"
)

type Admin struct {
	Id        int            `gorm:"primaryKey" json:"id" form:"id"`
	Account   string         `json:"account" form:"account"`
	Username  string         `json:"username"`
	Password  string         `json:"password"`
	RoleNames string         `json:"roleNames"`
	Tel       string         `json:"tel"`
	Email     string         `json:"email"`
	Sex       int            `json:"sex"`
	Status    int            `json:"stauts"`
	CreatedAt time.Time      `json:"createdAt"`
	UpdatedAt time.Time      `json:"updatedAt"`
	DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
}

// Info 获取一条数据
func (a *Admin) Info(args map[string]interface{}) *gorm.DB {
	info := Db.Where(args).First(a)
	return info
}

func (a *Admin) TableName() string {
	return TableName("admins")
}

func AdminAdd(a *Admin) (int64, error) {
	return orm.NewOrm().Insert(a)
}

func AdminGetByName(account string) (*Admin, error) {
	a := new(Admin)
	err := orm.NewOrm().QueryTable(a.TableName()).Filter("account", account).One(a)
	if err != nil {
		return nil, err
	}
	return a, nil
}

func AdminGetList(page, pageSize int, filters ...interface{}) ([]*Admin, int64) {
	offset := (page - 1) * pageSize
	list := make([]*Admin, 0)
	a := new(Admin)
	query := orm.NewOrm().QueryTable(a.TableName())
	if len(filters) > 0 {
		l := len(filters)
		for k := 0; k < l; k += 2 {
			query = query.Filter(filters[k].(string), filters[k+1])
		}
	}
	total, _ := query.Count()
	query.OrderBy("-id").Limit(pageSize, offset).All(&list)
	return list, total
}

func AdminGetById(id int) (*Admin, error) {
	a := new(Admin)
	err := orm.NewOrm().QueryTable(a.TableName()).Filter("id", id).One(a)
	if err != nil {
		return nil, err
	}
	return a, nil
}

func (a *Admin) Update(fields ...string) error {
	if _, err := orm.NewOrm().Update(a, fields...); err != nil {
		return err
	}
	return nil
}
